<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-03-10 20:16:59
 * @LastEditors: Sam
 * @LastEditTime: 2022-07-12 16:05:53
 */
namespace app\api\controller;
use app\admin\model\{Artist, Goods as GoodsModel,StoreCategory,GoodsAttr,GoodsCollection,GoodsComment,GoodsView};
use app\Request;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("商品模块")
 */
class Goods extends ApiBase{


    /**
     * @Apidoc\Title("商品分类")
     * @Apidoc\Url("/api/goods_category")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("[]", type="list[]",
	 * 	    @Apidoc\Returned("id", type="int",desc="分类id"),
	 * 		@Apidoc\Returned("cate_name", type="string",desc="分类名称"),
	 *	    @Apidoc\Returned("pic", type="string",desc="分类图片"),
	 * )
     */
	public function category()
    {
        $cateogry = StoreCategory::where('is_show', 1)->order('sort desc,id desc')->select();
        json_response(200,'success',arr_tree($cateogry->toArray(),true,0,['parent_key'=>'pid']));
    }

    /**
     * @Apidoc\Title("商品列表")
     * @Apidoc\Url("/api/goods_list")
     * @Apidoc\Method("GET")
	 * @Apidoc\param("cate_id", type="int",desc="商品分类"),
	 * @Apidoc\param("keyword", type="string",desc="关键字"),
	 * @Apidoc\param("page", type="int",desc="页码"),
	 * @Apidoc\param("limit", type="int",desc="数量"),
     * @Apidoc\Returned("[]", type="list[]",
	 * 	    @Apidoc\Returned("goods_id", type="int",desc="商品id"),
	 * 		@Apidoc\Returned("image", type="string",desc="商品图片"),
	 *	    @Apidoc\Returned("store_name", type="string",desc="商品名称"),
	 *      @Apidoc\Returned("store_info", type="string",desc="商品简介"),
	 * 		@Apidoc\Returned("price", type="string",desc="商品价格"),
	 * 		@Apidoc\Returned("unit_name", type="string",desc="单位"),
	 *      @Apidoc\Returned("sales", type="string",desc="销量"),
	 *      @Apidoc\Returned("stock", type="string",desc="库存"),
	 *      @Apidoc\Returned("browse", type="string",desc="浏览量"),
	 * )
     */
    public function goods_list(){
    	$data = request()->param();
    	$where = [];
    	if(isset($data['cate_id']) && $data['cate_id'] !=''){
    		$where[] = ['cate_id','=',$data['cate_id']];
    	}
    	if(isset($data['keyword']) && $data['keyword'] !=''){
    		$where[] = ['keyword|store_name','like',"%{$data['keyword']}%"];
    	}
    	$page  = request()->param('page/d',1);
 		$limit = request()->param('limit/d',10);
    	$list  = GoodsModel::with(['cate','artist','merchant'])->where('is_show',1)->where('goods_type',1)->where('is_del',0)->field('id as goods_id,cate_id,artist_id,image,store_name,store_info,price,unit_name,sales,stock,browse,goods_type')->where($where)->order('is_hot desc,is_new desc,sales desc')->page($page,$limit)->select();
    	json_response(200,'success',$list);
    }

	/**
	 * 热搜
	 *
	 * @return void
	 */
	public function search_goods_list(){
		$data = request()->param();
		$where = [];
		if(isset($data['keyword']) && $data['keyword'] !=''){
			$where[] = ['keyword|store_name','like',"%{$data['keyword']}%"];
		}
		$sort_type = isset($data['sort_type']) ? $data['sort_type'] : 0; //排序类型 0默认 1最新 2价格
		$sort_order = isset($data['sort_order']) ? $data['sort_order'] : 'desc'; //排序方向 asc或desc
		
		$page  = request()->param('page/d',1);
		$limit = request()->param('limit/d',10);
		
		if($sort_type == 0){
			$sort = 'sort '.$sort_order.',sales '.$sort_order;
		}
		if($sort_type == 1){
			$sort = 'is_new '.$sort_order.',id '.$sort_order;
		}
		if($sort_type == 2){
			$sort = 'price '.$sort_order.',sales '.$sort_order;
		}
		
		$list  = GoodsModel::with(['cate','artist'])
			->where('is_show',1)
			->where('is_del',0)
			->field('id as goods_id,cate_id,artist_id,image,store_name,store_info,price,unit_name,sales,stock,browse,goods_type')
			->order($sort)
			->where($where)
			->order('browse '.$sort_order.',sales '.$sort_order)
			->page($page,$limit)
			->select();
			
		json_response(200,'success',$list);
	}

	/**
	 * 搜索商品
	 *
	 * @return void
	 */
	public function search_goods(){
    	$data = request()->param();
    	$where = [];
		$sort  = '';
		$new_sort = isset($data['new_sort']) ? $data['new_sort'] : 0; //是否新品
		$price_sort = isset($data['price_sort']) ? $data['price_sort'] : 0; //价格排序 0不排序 1升序 2降序
		if($new_sort == 1){
			$sort .= 'is_new desc,';
		}
		if($price_sort == 1){
			$sort .= 'price asc,';
		}
		if($price_sort == 2){
			$sort .= 'price desc,';
		}
	
    	if(isset($data['keyword']) && $data['keyword'] !=''){
    		$where[] = ['keyword|store_name','like',"%{$data['keyword']}%"];
    	}
    	$page  = request()->param('page/d',1);
 		$limit = request()->param('limit/d',10);
    	$list  = GoodsModel::with(['cate','artist'])->where('is_show',1)->where('is_del',0)->field('id as goods_id,cate_id,artist_id,image,store_name,store_info,price,unit_name,sales,stock,browse,goods_type')->where($where)->order('is_hot desc,is_new desc,sales desc')->page($page,$limit)->select();
    	json_response(200,'success',$list);
    }

	/**
	 * 数字珍品
	 *
	 * @return void
	 */
	public function goods_list_digital(){
    	$data = request()->param();
    	$where = [];
    	$page  = request()->param('page/d',1);
 		$limit = request()->param('limit/d',10);
    	$list  = GoodsModel::with(['artist'])->where('is_show',1)->where('goods_type',2)->where('is_del',0)->field('id as goods_id,cate_id,artist_id,image,store_name,store_info,price,unit_name,sales,stock,browse,goods_type')->where($where)->order('is_hot desc,is_new desc,sales desc')->page($page,$limit)->select();
    	json_response(200,'success',$list);
    }
	

     /**
     * @Apidoc\Title("商品详情")
     * @Apidoc\Url("/api/goods_detail")
     * @Apidoc\Method("GET")
	 * @Apidoc\Param("goods_id", type="int",desc="商品id"),
     * @Apidoc\Returned("goods_info", type="object",desc="商品详情",
	 * 	    @Apidoc\Returned("id", type="int",desc="商品id"),
	 * 		@Apidoc\Returned("image", type="string",desc="商品图片"),
	 * 		@Apidoc\Returned("slider_image", type="[]",desc="商品轮播图"),
	 *	    @Apidoc\Returned("store_name", type="string",desc="商品名称"),
	 *      @Apidoc\Returned("store_info", type="string",desc="商品简介"),
	 *      @Apidoc\Returned("keyword", type="string",desc="商品关键字"),
	 * 		@Apidoc\Returned("price", type="string",desc="商品价格"),
	 * 		@Apidoc\Returned("unit_name", type="string",desc="单位"),
	 *      @Apidoc\Returned("sales", type="string",desc="销量"),
	 *      @Apidoc\Returned("stock", type="string",desc="库存"),
	 *      @Apidoc\Returned("browse", type="string",desc="浏览量"),
	 *      @Apidoc\Returned("description", type="text",desc="详情"),
	 *      @Apidoc\Returned("spec_type", type="int",desc="规则 0单规格 1多规格"),
	 *      @Apidoc\Returned("is_collection", type="int",desc="是否已收藏 0 未收藏 1已收藏"),
	 *      @Apidoc\Returned("all_comments", type="int",desc="评论量"),
	 * 		@Apidoc\Returned("comments", type="list[]",desc="评论列表",
	 * 					@Apidoc\Returned("comment_id", type="int",desc="评论ID"),
	 * 					@Apidoc\Returned("comments", type="string",desc="评论内容"),
	 * 					@Apidoc\Returned("images", type="list[]",desc="评论图片")
	 * 		)
	 * )
	* @Apidoc\Returned("productAttr", type="list[]",desc="商品规格显示",
	 * 	    @Apidoc\Returned("product_id", type="int",desc="商品id"),
	 * 		@Apidoc\Returned("attr_name", type="string",desc="规则名称"),
	 * 		@Apidoc\Returned("attr_values", type="list[]",desc="规格值"),
	 *	    @Apidoc\Returned("attr_value", type="list[]",desc="处理后的规格值 方面前端读取",
	 *					 @Apidoc\Returned("attr", type="string",desc="显示值"),
	 *					 @Apidoc\Returned("check", type="bool",desc="是否选中")
	 *		)
	 * )
	 *@Apidoc\Returned("productValue", type="list[]",desc="选择规格生成的商品列表 用户选择完成后生成作为后续传值",
	 * 				@Apidoc\Returned("product_id", type="int",desc="商品ID"),
	 * 				@Apidoc\Returned("stock", type="int",desc="库存"),
	 * 				@Apidoc\Returned("suk", type="string",desc="suk"),
	 * 				@Apidoc\Returned("image", type="string",desc="图片"),
	 * 				@Apidoc\Returned("unique", type="string",desc="商品唯一标识"),
	 * 				@Apidoc\Returned("price", type="string",desc="价格"),
	 * 				@Apidoc\Returned("ot_price", type="string",desc="原价")
	 * 		)
	 * 
     */
    public function detail(){

    	$goods_id = param_check('goods_id');
    	$uid      = $this->get_user_id();
    	$goods_info   = GoodsModel::with(['merchant'])->where('is_show',1)->where('id',$goods_id)->where('stock','>',0)->field('id,image,goods_type,artist_id,slider_image,store_name,store_info,keyword,cate_id,price,ot_price,unit_name,sales,stock,spec_type,description')->find();
    	if(!$goods_info) json_response(400,'商品已下架或不存在');
    	list($productAttr, $productValue) = GoodsAttr::getProductAttrDetail($goods_id);
        if (!$goods_info['spec_type']) {
            $productAttr  = [];
            $productValue = [];
        }
		$goods_info->browse +=1;
		$goods_info->save();
		$goods_info->is_collection = GoodsCollection::where(['uid'=>$uid,'goods_id'=>$goods_id])->count() ? true :false;
		$goods_info->comments      = GoodsComment::where(['goods_id'=>$goods_id,'is_show'=>1,'status'=>1])->field('id as comment_id,uid,goods_id,comments,images,nickname,avatar,create_time,level')->order('is_top desc,id desc')->limit(10)->select();
		$goods_info->all_comments   = GoodsComment::where('goods_id',$goods_id)->where('status',1)->where('is_show',1)->count();
		$goods_info->slider_image_arr = $goods_info->slider_image ? explode(',', $goods_info->slider_image) : [];
		$goods_info->artist_detail  = Artist::find($goods_info->artist_id);
		// $similar_goods   =  GoodsModel::with(['cate'])->where('is_show',1)->where('id','<>',$goods_id)->where('cate_id',$goods_info->cate_id)->where('stock','>',0)->field('id as goods_id,cate_id,image,store_name')->order('is_hot desc,is_new desc,sales desc')->limit(10)->select();
		// $view_goods      = GoodsView::with(['goods'])->where('uid',$uid)->order('id desc')->limit(10)->field('goods_id,uid')->select();
		if(!GoodsView::where(['uid'=>$uid,'goods_id'=>$goods_id])->count()){
			GoodsView::create([
				'uid' => $uid,
				'goods_id' => $goods_id
			]);
		}
    	json_response(200,'success',compact('goods_info','productAttr','productValue'));
    }

	/**
	 * 推荐商品
	 *
	 * @return void
	 */
	public function recommend_goods(Request $request){
		$goods_id = $request->param('goods_id/d',0);
		$where    = [];
		$where[]  = ['is_show','=',1];
		$where[]  = ['stock','>',0];
		if($goods_id > 0){
			$where[] = ['id','<>',$goods_id];
			$goods_info = GoodsModel::where('is_show',1)->where('id',$goods_id)->where('stock','>',0)->field('id,cate_id')->find();
			if($goods_info){
				$where[] = ['cate_id','=',$goods_info->cate_id];
			}
		}
		$similar_goods = GoodsModel::with(['cate','artist'])->where($where)->field('id as goods_id,cate_id,image,store_name,artist_id,price')->order('is_hot desc,is_new desc,sales desc')->limit(10)->select();
		json_response(200,'success',$similar_goods);
	}

	/**
	 * 最近浏览
	 *
	 * @param Request $request
	 * @return void
	 */
	public function view_goods(Request $request){
		$uid      = $this->get_user_id();
		$where    = [];
		$list     = [];
		$goods_id  = GoodsView::where('uid',$uid)->order('id desc')->column('goods_id');
		if(count($goods_id)){
			$where[] = ['id','in',$goods_id];
			$list = GoodsModel::with(['cate','artist'])->where($where)->field('id as goods_id,cate_id,image,store_name,artist_id,price')->order('is_hot desc,is_new desc,sales desc')->limit(10)->select();
		}
		json_response(200,'success',$list);
	}

	/**
     * @Apidoc\Title("商品收藏")
     * @Apidoc\Url("/api/goods_collection")
     * @Apidoc\Method("POST")
	 * @Apidoc\Param("goods_id", type="int",require=true, desc="商品id")
	 * @Apidoc\Param("type", type="int",desc="1 添加 2取消")
     */
	public function goods_collection() {
		$goods_id = param_check('goods_id');
		$type     = request()->param('type/d', 1); // 1添加 2取消
	
		if (!$goods = GoodsModel::where('id', $goods_id)->find()) {
			return json_response(400, '商品不存在');
		}
	
		$uid = $this->get_user_id();
		$result = GoodsCollection::where(['uid' => $uid, 'goods_id' => $goods_id])->field('id')->find();
	
		if ($type == 1) {
			// 收藏
			if (!$result) {
				try {
					$res = GoodsCollection::create(['uid' => $uid, 'goods_id' => $goods_id,'goods_type' => $goods->goods_type]);
				} catch (\Exception $e) {
					return json_response(400, '收藏失败：' . $e->getMessage());
				}
			} else {
				return json_response(400, '已经收藏了');
			}
		} else {
			// 取消收藏
			if ($result) {
				$res = $result->delete();
			} else {
				return json_response(400, '尚未收藏，无需取消');
			}
		}
	
		if ($res) return json_response(200, '操作成功');
		return json_response(400, '操作失败');
	}
	


	/**
     * @Apidoc\Title("我的商品收藏")
     * @Apidoc\Url("/api/my_collection")
     * @Apidoc\Method("get")
	 * @Apidoc\Param("page", type="int",desc="页码")
	 * @Apidoc\Param("limit", type="int",desc="数量")
	 * @Apidoc\Param("name", type="string",desc="商品名称")
	 * @Apidoc\Returned("[]", type="object",desc="商品列表",
	 * 		@Apidoc\Returned("goods_id", type="int",desc="商品id"),
	 * 		@Apidoc\Returned("image", type="string",desc="商品图片"),
	 * 		@Apidoc\Returned("store_name", type="string",desc="商品"),
	 * 		@Apidoc\Returned("price", type="string",desc="商品价格")
	 * )
     */
	public function my_collection(){
		$uid 	 = $this->get_user_id();
		$page    = request()->get('page/d',1);
		$limit   = request()->get('limit/d',10);
		$name    = request()->get('name','');
		$goods_type = request()->get('goods_type/d',1); //商品类型 1普通商品 2数字藏品
		$where   = [];
		$where[] = ['uid','=',$uid];
		if($name){
			$gids = GoodsModel::where('store_name','like',"%{$name}%")->column('id');
			$where[] = ['goods_id','in',$gids];
		}
		if($goods_type > 0){
			$where[] = ['goods_type','=',$goods_type];
		}
		$lst = GoodsCollection::with('goods')->where($where)->page($page,$limit)->order('id desc')->field('id,goods_id')->hidden(['goods'])->select();
		json_response(200,'success',$lst);
	}
}